package tchatrmi;

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * Tchat en Java RMI
 * @author Toto
 * @version 1.0
 */
public class IHM implements ActionListener {

   private JTextArea entrants;
   private JTextField sortants;
   private ArrayList<String> sendMessages = new ArrayList<String>();

   public void go() {	
	JFrame cadre = new JFrame ("Client de discussion");
	JPanel panneau = new JPanel ();
	entrants = new JTextArea (15,30);
	entrants.setLineWrap (true);
	entrants.setWrapStyleWord (true);
	entrants.setEditable (false);
	JScrollPane zoneTexte = new JScrollPane (entrants);
	zoneTexte.setVerticalScrollBarPolicy
					(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
	zoneTexte.setHorizontalScrollBarPolicy 
					(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
	sortants = new JTextField (24);
	JButton boutonEnvoi = new JButton ("Envoi");
	boutonEnvoi.addActionListener (this);
	panneau.add (zoneTexte);
	panneau.add (sortants);
	panneau.add (boutonEnvoi);
	cadre.getContentPane ().add (BorderLayout.CENTER, panneau);
	cadre.setSize (400,310);
	cadre.setVisible (true);
	
	panneau.setLayout(new BoxLayout(panneau, BoxLayout.Y_AXIS));
	cadre.pack();
   } // fin methode go

   synchronized  public void  actionPerformed (ActionEvent ev) {
	sendMessages.add(sortants.getText ());			 	
	sortants.setText ("");
	sortants.requestFocus ();
	this.notify();
   }

   synchronized public String getNextMessageToSend() {
	try{
	    if(sendMessages.isEmpty()) this.wait();	   
	}
	catch(Exception ex) {ex.printStackTrace();}
	String mess = (String) sendMessages.remove(0);
	System.out.println("IHM -> message a envoyer : " + mess);
	return mess;
   }

   public void writeMessage(String mess) {
	System.out.println ("IHM -> message a ecire : " + mess);
	entrants.append (mess + "\n");
   }

   public static void main (String[] args) {	
	IHM client = new IHM ();
	client.go ();
	String mess;
	while(true) {
	    mess = client.getNextMessageToSend();
	    System.out.println(mess);
	    client.writeMessage(mess);
	}
   }

} // fin classe SimpleClientDiscussion
